package com.nanhang.controller;

import com.nanhang.common.util.PageResult;
import com.nanhang.common.util.R;
import com.nanhang.entity.Student;
import com.nanhang.service.IStudentService;
import com.nanhang.vo.StudentVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/student")
public class StudentController {

	// 自动装配学生服务接口
	@Autowired
	private IStudentService studentService;

	/**
	 * 获取所有学生信息
	 * @return 返回包含学生列表的响应结果
	 */
	@RequestMapping("/list")
	public R getStudent() {
		List<Student> studentList = studentService.list();
		return R.ok().data("list", studentList);
	}

	/**
	 * 分页查询学生信息
	 * @param page 当前页码
	 * @param pageSize 每页显示数量
	 * @return 返回包含分页结果的响应结果
	 */
	@GetMapping("/findByPage/{page}/{pageSize}")
	public R findByPage(@PathVariable("page") Integer page,
						@PathVariable("pageSize") Integer pageSize) {
		PageResult<Student> pageResult = studentService.findByPage(page, pageSize);
		return R.ok().data("pr", pageResult);
	}


	@PostMapping("/search/{page}/{pageSize}")
	public R search(@PathVariable("page") Integer page,
					@PathVariable("pageSize") Integer pageSize,
					@RequestBody(required = false) StudentVO vo) {
		PageResult<Student> pageResult = studentService.search(page, pageSize, vo);
		return R.ok().data("pr", pageResult);
	}

	@PostMapping("/add")
	public R add(@RequestBody Student student) {
		boolean isAdded = studentService.add(student);
		if (isAdded) {
			return R.ok().message("添加成功");
		}
		return R.error().message("添加失败");
	}


 -   @PutMapping("/update")
	public R update(@RequestBody Student student) {
		boolean isUpdated = studentService.updateById(student);
		if (isUpdated) {
			return R.ok().message("修改成功");
		}
		return R.error().message("修改失败");
	}


	@DeleteMapping("/delete/{ids}")
	public R delete(@PathVariable("ids") String ids) {
		String[] idArray = ids.split(",");
		List<String> studentIds = Arrays.asList(idArray);
		boolean isDeleted = studentService.removeByIds(studentIds);
		if (isDeleted) {
			return R.ok().message("删除成功");
		}
		return R.error().message("删除失败");
	}
}


